//
//  DashLineView.swift
//  Yip
//
//  Created by bo wang on 2022/6/6.
//  Copyright © 2022 yip.com. All rights reserved.
//

import UIKit

class DashLineView: UIView {

    @IBInspectable var dashLength: CGFloat = 10 {
        didSet {
            updateDashLayer()
        }
    }
    @IBInspectable var dashSpacing: CGFloat = 10 {
        didSet {
            updateDashLayer()
        }
    }
    @IBInspectable var dashColor: UIColor = .black {
        didSet {
            updateDashLayer()
        }
    }
    
    private lazy var dashLayer: CAShapeLayer = {
        let l = CAShapeLayer()
        l.frame.origin = .zero
        return l
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        updateDashLayer()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        updateDashLayer()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        updateDashLayer()
    }
    
    func updateDashLayer() {
        dashLayer.frame = bounds
        layer.insertSublayer(dashLayer, at: 0)
        
        dashLayer.strokeColor = dashColor.cgColor
        dashLayer.lineDashPattern = [NSNumber(value: dashLength), NSNumber(value: dashSpacing)]
        if bounds.width < bounds.height {
            dashLayer.lineWidth = bounds.width
            let path = UIBezierPath()
            path.move(to: CGPoint(x: bounds.width / 2, y: 0))
            path.addLine(to: CGPoint(x: bounds.width / 2, y: bounds.height))
            dashLayer.path = path.cgPath
        } else {
            dashLayer.lineWidth = bounds.height
            let path = UIBezierPath()
            path.move(to: CGPoint(x: 0, y: bounds.height / 2))
            path.addLine(to: CGPoint(x: bounds.width, y: bounds.height / 2))
            dashLayer.path = path.cgPath
        }
    }
}
